昨天我們提到了,DuckDB 支援了 list comprehension
複習一下昨天的 DuckDB SQL 把咒術迴戰裡面名子有 'to' 的角色挑出來
SELECT
id,
names,
[name FOR name IN names IF name.lower().contains('to')] AS filtered_names
FROM (
VALUES
(1, ['Gojo Satoru', 'Itadori Yuji', 'Fushiguro Megumi', 'Kugisaki Nobara']),
(2, ['Sukuna', 'Nanami Kento', 'Todo Aoi']),
(3, ['Maki Zenin', 'Inumaki Toge'])
) AS sorcery_battle(id, names);
精華在於這句[name FOR name IN names IF name.lower().contains('to')] AS filtered_names
基本上語法和 Python 一模一樣。
不過事情還遠遠沒有結束, Python 中常常與 list comprehension 一起花式使用的功能就是 lambda
# list comprehension
[name FOR name IN names IF name.lower().contains('to')]
# lambda
filter(lambda name: 'to' in name.lower(), names)
相信又被聰明的讀者猜到了,DuckDB 支援 lambda funciton
所以可以這麼寫
SELECT
id,
names,
list_filter(names, name -> name.lower().contains('to')) AS filtered_names
FROM (
VALUES
(1, ['Gojo Satoru', 'Itadori Yuji', 'Fushiguro Megumi', 'Kugisaki Nobara']),
(2, ['Sukuna', 'Nanami Kento', 'Todo Aoi']),
(3, ['Maki Zenin', 'Inumaki Toge'])
) AS sorcery_battle(id, names);
list_filter(names, name -> name.lower().contains('to')) AS filtered_names
是不是寫起來很有 python + java 的混合體
#python
filter(lambda name: 'to' in name.lower(), names)
#java
names.stream()
.filter(name -> name.toLowerCase().contains("to"))
.collect(Collectors.toList());
#DuckDB
list_filter(names, name -> name.lower().contains('to'))
我真的超愛這種 python + java 語法的混合體。 ->
來當作 lambda keyword 看起來真的舒服。
趕快到 DuckDB WASM 或 Colab 試試看吧,神奇的 duckdb lambda 吧!
SELECT
id,
names,
filter(names, name -> name.lower().contains('to')) AS filtered_names
FROM (
VALUES
(1, ['Gojo Satoru', 'Itadori Yuji', 'Fushiguro Megumi', 'Kugisaki Nobara']),
(2, ['Sukuna', 'Nanami Kento', 'Todo Aoi']),
(3, ['Maki Zenin', 'Inumaki Toge'])
) AS sorcery_battle(id, names);
除此之外,我在今天的例子中,埋了一個小伏筆喔,細心的讀者有發現這麼多個例子中,有哪裡不一樣,趕快留言告訴我。